// pages/home/home.js
var app = getApp();
const util = require('../../utils/util.js');
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showImage: true,
    showMain: false,
    imageList: [
      // { url: '/static/image/scan.png', urlClose: '/static/image/scan.png', type: false, class: 'imgscan', title: '扫一扫', val: '' },
      { url: '/static/image/img5.png', urlClose: '/static/image/imgc5.png', type: false, class: 'img0', title: '负离子', val: '' },
      { url: '/static/image/lamp.png', urlClose: '/static/image/lampc.png', type: false, class: 'imgscan', title: '指示灯' },
      { url: '/static/image/img0.png', urlClose: '/static/image/imgc0.png', type: false, class: 'img1', title: '零档' },
      { url: '/static/image/img1.png', urlClose: '/static/image/imgc1.png', type: false, class: 'img2', title: '一档' },
      { url: '/static/image/img2.png', urlClose: '/static/image/imgc2.png', type: false, class: 'img3', title: '二档' },
    ],
    blueToothIsOpen: false,
    bleList: null,//蓝牙读取的数据
    timer: '',
    hex: '',
    bleData: '',
    showType: false,//loading是否显示
    onBleValType: false,//是否是断开监听蓝牙返回数据
    writeType: false,//代表是点击蓝牙读取的数据
    flag:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.clearStorageSync()
    let that = this
    let showImage = that.data.showImage
    let showMain = that.data.showImage
    setTimeout(() => {
      showImage = false
      that.setData({ showImage })
    }, 3000);
    setTimeout(() => {
      showMain = true
      that.setData({ showMain })
    }, 1000);
    if (!wx.getStorageSync('blueToothType')) {
      setTimeout(() => {
        wx.showModal({
          title: '提示',
          content: '当前未连接设备，是否连接！',
          success: res => {
            console.log(res)
            if (res.confirm) {
              this.nextBlueTooth()
            }
          }
        })
      }, 3010)

    }
    if (wx.getStorageSync('blueToothIsOpen') && wx.getStorageSync('blueToothType')) {
      wx.openBluetoothAdapter({
        success: (res) => {
          console.log('openBluetoothAdapter success', res)
          // this.createBLEConnection()
        },
      })

    }
    this.readBle()
  },
  nextBlueTooth: function () {
    wx.navigateTo({
      url: '../blueTooth/blueTooth'
    })
  },
  nextBlueDetail: function () {
    wx.navigateTo({
      url: '../detail/detail'
    })
  },
  blueToothClose: function () {
    wx.closeBLEConnection({
      deviceId: wx.getStorageSync('deviceId')
    })
    wx.setStorageSync('blueToothIsOpen', false)
    this.setData({
      blueToothIsOpen: false
    })
  },
  blueToothOpen: function () {
    this.createBLEConnection()
    wx.showLoading({
      title: '蓝牙正在连接中...',
    })
    this.setData({
      showType: true
    })

  },
  touchStart:function(e){
    console.log(e,e.timeStamp)
  },
  touchEnd:function(e){
    console.log(e.timeStamp)
  },
  writeData: function (e) {
    if(!this.data.flag){
      return
    }
    if (!this.data.blueToothIsOpen) {
      // util.toast('设备未连接！')
      wx.showModal({
        title: '提示',
        content: '当前未连接设备，是否连接！',
        success: res => {
          console.log(res)
          if (res.confirm) {
            this.nextBlueTooth()
          }
        }
      })
      return
    }
    wx.openBluetoothAdapter({
      fail: (res) => {
        wx.showModal({
          content: '请开启手机蓝牙后再试',
          success: () => {
            return false
          }
        })
      }
    })
    let list = this.data.imageList
    let index = e.currentTarget.dataset.index
    this.setData({ 
      writeType: true ,
      flag:false
    })
    if (this.data.onBleValType) {
      wx.offBLECharacteristicValueChange(res => {
        console.log(res, '取消蓝牙监听')
      })
      this.setData({
        onBleValType: true
      })
    }
    let hex = ''
    switch (index) {
      case 0:
        hex = list[index].type ? '0x520x00' : '0x520x01'
        // list[index].type ? list[index].type = false : list[index].type = true
        break;
      case 1:
        hex = list[index].type ? '0x580x00' : '0x580x01'
        // list[index].type ? list[index].type = false : list[index].type = true
        break;
      case 2:
        console.log('0', index, list[3].type, list[4].type, list)
        hex = '0x500x00'
        // list[index].type ? '' : list[index].type = true, list[3].type = false, list[4].type = false
        break;
      case 3:
        hex = '0x500x01'
        // list[index].type ? '' : list[index].type = true, list[2].type = false, list[4].type = false
        break;
      case 4:
        hex = '0x500x02'
        // list[index].type ? '' : list[index].type = true, list[2].type = false, list[3].type = false
        break;
    }
    this.setData({
      imageList: list,
      hex: this.string2buffer(hex)
    })
    setTimeout(()=>{
      this.setData({flag:true})
    },500)
    console.log(hex, wx.getStorageSync('deviceId'), wx.getStorageSync('serviceId'), wx.getStorageSync('characteristicId'), this.string2buffer(hex))
    this.getBLEDeviceCharacteristics(wx.getStorageSync('deviceId'), wx.getStorageSync('serviceId'), this.string2buffer(hex))
  },
  readBle: function () {
    let timer = setInterval(() => {
      if (app.globalData.blueToothList != null) {
        this.setData({
          bleList: app.globalData.blueToothList
        })
        // console.log(this.data.bleList)
      }
    }, 1000)
    this.setData({ timer })
  },
  // 连接蓝牙低功耗设备
  createBLEConnection() {
    const deviceId = wx.getStorageSync('deviceId')
    if (deviceId != '') {
      wx.openBluetoothAdapter({
        success: res => {

        }
      })
    }
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({ writeType: false })
        this.getBLEDeviceServices(deviceId)
      }
    })
  },
  // 获取蓝牙低功耗设备所有服务 (service)。
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log(res.services)
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[1].uuid)
            return
          }
        }
      }
    })
  },
  // 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
  getBLEDeviceCharacteristics(deviceId, serviceId, hex) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', serviceId, res)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.write) {
            this.writeBLECharacteristicValue(deviceId, serviceId, item.uuid, hex)
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
              success: (res) => {
                // 操作之前先监听，保证第一时间获取数据
                console.log(res)
                if (this.data.showType) {
                  wx.hideLoading()
                }
                // util.toast('设备已连接！')
                wx.setStorageSync('blueToothIsOpen', true)
                this.setData({
                  blueToothIsOpen: true,
                  showType: false
                })
              },
              fail: res => {
                console.log(res)
              }
            })
          }

        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    wx.onBLECharacteristicValueChange((resItem) => {
      let str = ab2hex(resItem.value)
      console.log(util.splitString(str))
      let data = util.pushArr(util.splitString(str))
      let imageList = this.data.imageList
      console.log(data)
      imageList[2].type = false
      imageList[3].type = false
      imageList[4].type = false
      imageList[Number(data.fanType) + 2].type = true
      data.anionType == '1' ? imageList[0].type = true : imageList[0].type = false
      data.lamp == '1' ? imageList[1].type = true : imageList[1].type = false

      console.log(imageList)
      this.setData({
        bleData: data,
        imageList: imageList,
        writeType: false,
        flag:true
      })
    })
  },
  // 向蓝牙设备发送一个0x00的16进制数据
  writeBLECharacteristicValue(deviceId, serviceId, characteristicId, hex) {

    // let hex = this.string2buffer('0x60')
    // console.log(this._deviceId, this._serviceId, this._characteristicId, hex)
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: hex,
      success: res => {
        console.log(res)

      },
      fail: res => {
        console.log(res)
      }
    })
  },
  // 将数据转换为16禁制
  string2buffer(str) {
    let val = ""
    if (!str) return;
    let length = str.length;
    let index = 0;
    let array = []
    while (index < length) {
      array.push(str.substring(index, index + 2));
      index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(wx.getStorageSync('blueToothType'), wx.getStorageSync('blueToothIsOpen'), wx.getStorageSync('blueToothType') && wx.getStorageSync('blueToothIsOpen') ? true : false)
    if (!wx.getStorageSync('blueToothType')) {
      this.setData({
        blueToothIsOpen: wx.getStorageSync('blueToothType') && wx.getStorageSync('blueToothIsOpen') ? true : false,
      })
    } else {
      let num = 0
      var flag =  setInterval(()=>{
        num++
        console.log(num)
        if(num > 30){
          wx.closeBLEConnection({
            deviceId: wx.getStorageSync('deviceId'),
          })
          wx.clearStorageSync()
          this.setData({
            blueToothIsOpen:false
          })
          clearInterval(flag)
        }
        
      },1000)
      // this.createBLEConnection()
      wx.onBLECharacteristicValueChange((resItem) => {
        num = 0 
        let str = ab2hex(resItem.value)
        let defectStr = str.length < 30 ? str : ''
        str = str + defectStr
        console.log(str)
        if(str.slice(0,2) == '53' && str.length == 40){
          setTimeout(()=>{
            console.log(util.splitString(str))
            console.log(util.splitArr(util.splitString(str)))
            console.log(util.splitString(defectStr))
            console.log(data,'数组为20位时')
            let data = (util.splitArr(util.splitString(str))).concat(util.splitString(defectStr))
            console.log(data)
            let imageList = this.data.imageList
            imageList[2].type = false
            imageList[3].type = false
            imageList[4].type = false
            imageList[Number(data.fanType) + 2].type = true
            data.anionType == '1' ? imageList[0].type = true : imageList[0].type = false
            data.lamp == '1' ? imageList[1].type = true : imageList[1].type = false
            console.log(imageList)
            this.setData({
              bleData: data,
              imageList: imageList,
              writeType: false
            })
          },0)
          
        }else{
          console.log('数组为15位时')
          console.log(util.splitString(str))
          let data = util.pushArr(util.splitString(str))
          let imageList = this.data.imageList
          console.log(data)
          imageList[2].type = false
          imageList[3].type = false
          imageList[4].type = false
          imageList[Number(data.fanType) + 2].type = true
          data.anionType == '1' ? imageList[0].type = true : imageList[0].type = false
          data.lamp == '1' ? imageList[1].type = true : imageList[1].type = false
          console.log(imageList)
          this.setData({
            bleData: data,
            imageList: imageList,
            writeType: false
          })
        }
      })
      this.setData({
        blueToothIsOpen: wx.getStorageSync('blueToothType') && wx.getStorageSync('blueToothIsOpen') ? true : false,
      })
      this.writeBLECharacteristicValue(wx.getStorageSync('deviceId'), wx.getStorageSync('serviceId'), wx.getStorageSync('characteristicId'), this.string2buffer('0x5E0x01'))
    }



    // console.log(this.data.blueToothIsOpen)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('离开当前页面')
    wx.offBLECharacteristicValueChange((res) => {
      console.log(res, '离开当前页面')
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})